package com.lych.dubbo.api;

import com.lych.model.mongo.Comment;
import com.lych.model.mongo.CommentVideo;
import com.lych.model.mongo.Video;
import com.lych.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentVideoApiImpl implements CommentVideoApi{

    @Autowired
    private MongoTemplate mongoTemplate;



    /**
     * 评论列表分页查询
     * @param id
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<CommentVideo> idComments(String id, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(id)))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,CommentVideo.class);
    }

    /**
     * 视频评论保存
     * @param comment1
     */
    @Override
    public void save(CommentVideo comment1) {
        //查询视频详细信息
        Video video = mongoTemplate.findById(comment1.getPublishId(), Video.class);
        if (video != null) {
            //向comment对象设置被评论人属性
            comment1.setPublishUserId(video.getUserId());
        }
        //保存到数据库
        mongoTemplate.save(comment1);
        //更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment1.getPublishId()));
        Update update = new Update();
        update.inc("commentCount",1);
        mongoTemplate.updateFirst(query,update,CommentVideo.class);
    }

    /**
     * 增加评论点赞数
     */
    @Override
    public void commentsIdLike(String publishId) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Update update = new Update();
        update.inc("likeCount",1);
        mongoTemplate.updateFirst(query,update,CommentVideo.class);
    }

    /**
     * 删除评论点赞数
     * @param publishId
     */
    @Override
    public void commentsIdDislike(String publishId) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Update update = new Update();
        update.inc("likeCount",-1);
        mongoTemplate.updateFirst(query,update,CommentVideo.class);
    }
}
